/*
 * @package	educME
 * @copyright (c) Jose Raul Perez 2011 under GPL
 */

function assignment(checknum, iframe, params) {

    var loading = loadingWindow();

    // call to php function
    eyeos.callMessage(checknum, 'getAssignment', params.id, function (rPars) {
        loading.destroy();
        
        // TODO eval is not safe !!
	var object = eval('(' + rPars + ')');

        var assignment = new Object;
        assignment = object.assignment.assignments[0];
        assignment.submission = object.submission[0];

        var win = new qx.ui.window.Window("Assignment",
                "index.php?extern=/images/moodle/theme/ico/page_white_edit.png");

        win.setLayout( new qx.ui.layout.Grow(0) );
        win.setAllowMinimize(false);
        win.setAllowMaximize(true);
//        win.setContentPadding(0);
        win.setWidth(800);
        win.setHeight(500);

        // scroller
        var scroller = new qx.ui.container.Scroll();
        win.add(scroller, {edge : 0});
        
        switch (assignment.assignmenttype) {
            case "offline":
                mainContainer = base(iframe, assignment);
                break;
            case "online":
                // we want height more big here
                mainContainer = onlineText( base(iframe, assignment), assignment, checknum );
                break;
            case "uploadsingle":
                mainContainer = singleFile( base(iframe, assignment), assignment, checknum );
                break;
            case "upload":
                mainContainer = singleFile( base(iframe, assignment), assignment, checknum );
                break;
        }

        scroller.add(mainContainer);
        
        win.center();
	win.open();
    });
} 
 
 
/*
 * There are four types of assignments.
 * Decorator pattern.
 */
 
 /*
 * To be decorated.
 */
function base(iframe, assignment) {

    // main container
    var mainContainer = new qx.ui.container.Composite(new qx.ui.layout.VBox(10)).set({
        allowShrinkY: false,
        paddingRight:10
    });

    // available from
    mainContainer.add(new qx.ui.basic.Label().set({
            value: "<strong>Available from: </strong>" + readableDate(assignment.timeavailable),
            rich : true,
            font: new qx.bom.Font.fromString("11px sans-serif"),
            textColor: "#666"
        })
    );

    // Due date:
    mainContainer.add(new qx.ui.basic.Label().set({
            value: "<strong>Due date: </strong>" + readableDate(assignment.timedue),
            rich : true,
            font: new qx.bom.Font.fromString("11px sans-serif"),
            textColor: "#666"
        })
    );

    // Intro:
    var container = new qx.ui.container.Composite(new qx.ui.layout.VBox(0)).set({
        decorator: "group"
    });
    container.add(new qx.ui.basic.Label().set({
            value: "<strong>" + assignment.name + "</strong><br />" + assignment.description,
            rich : true,
            font: new qx.bom.Font.fromString("12px sans-serif"),
            textColor: "#666",
            padding: 10
        })
    );
    mainContainer.add(container);
    
    // center in page
    return mainContainer;
}

/*
 * Decorator: Offline activity
 * Nothing to add
 */
function offlineActivity(mainContainer) {
    return mainContainer;
}

/*
 * Decorator: Online text
 * Add a text writer and some buttons
 */
function onlineText(mainContainer, assignment, checknum) {
    // box
    var buttons = new qx.ui.container.Composite(new qx.ui.layout.HBox(5));

    // buttons
    var save = new qx.ui.form.Button("Save changes", "index.php?extern=/images/moodle/theme/ico/disk.png");

    // if is in time to send submission
    if (assignment.timedue > Math.round( new Date().getTime() / 1000 )) {
        buttons.add(save);
    }    

    mainContainer.add(buttons);

    // if have been modified (timemodified is never 0)
    var lastEdit = new qx.ui.basic.Label().set({
        rich : true,
        font: new qx.bom.Font.fromString("11px sans-serif"),
        textColor: "green",
        paddingTop: 6

    });
 
    if (assignment.submission.timemodified != 0) {
        lastEdit.setValue( "<strong>Last edition:</strong> " + readableDate(assignment.submission.timemodified) );
        buttons.add(lastEdit);
    }    
    
    // writer box
  //  var htmlEditor = htmlArea(assignment.submission.data1);
    
//    mainContainer.add(htmlEditor, {flex:1});
    var editor = new demobrowser.demo.widget.HtmlArea(assignment.submission.data1);
    mainContainer.add(editor.__container, {flex:1});

    // save submission
    save.addListener("execute", function(e) {
        // don't press!
        save.setEnabled(false);

	var loading = new qx.ui.basic.Image("index.php?extern=/images/moodle/theme/ajax-loader.gif").set({
            paddingTop:5
        });
        assignment.submission.data1 = editor.__htmlArea.getComputedValue();
        buttons.add(loading);

        // if submission is empty, we create new one
         if (assignment.submission.id == 0) {

            assignment.submission.assignment = assignment.id;
            assignment.submission.assignmenttype = assignment.assignmenttype;
//            assignment.submission.userid = 2; // TODO
            assignment.submission.timecreated =  new Date().getTime();
            assignment.submission.data1 = editor.__htmlArea.getComputedValue();
//            assignment.submission.username = "admin"; // TODO
//            assignment.submission.useremail = "yakukubu@hotmail.com"; // TODO

        }
		
	// send submission
	eyeos.callMessage(checknum, 'updateSubmission', assignment.submission, function (rPars) {

            buttons.remove(loading);
			
            lastEdit.setValue("<strong>Last edition:</strong> " + readableDate( Math.round( new Date().getTime() / 1000 ) ));
			
			if (buttons.indexOf(lastEdit) == "-1") {
				buttons.add(lastEdit);
				
				// Qooxdoo has little delay adding, so we must wait a little to get the DOM of the label
				lastEdit.addListener('appear', function() {
					var pulsate = new qx.fx.effect.combination.Pulsate(lastEdit.getContentElement().getDomElement());
					pulsate.start();
				});
			
            } else {
				var pulsate = new qx.fx.effect.combination.Pulsate(lastEdit.getContentElement().getDomElement());
				pulsate.start();
			}			
			
            // you can press again
            save.setEnabled(true);
	}, this);
    });

    return mainContainer;
}

/*
 * Decorator: Upload a single file
 */
function singleFile(mainContainer, assignment, checknum) {
    /** boxes */
    // choose file button
    var box1 = new qx.ui.container.Composite(new qx.ui.layout.HBox(5));
    // save & cancel button
    var box2 = new qx.ui.container.Composite(new qx.ui.layout.HBox(5));

    // buttons
    var chooseFile = new qx.ui.form.Button("Upload a File", "index.php?extern=images/16x16/actions/document-open.png");
    var save = new qx.ui.form.Button("Save changes", "index.php?extern=/images/moodle/theme/ico/disk.png");
    var cancel = new qx.ui.form.Button("Cancel", "index.php?extern=images/16x16/actions/dialog-close.png");

    // file
    var file = new qx.ui.basic.Atom("", "index.php?extern=images/16x16/mimetypes/application-x-zerosize.png").set({
        backgroundColor : "#E6FAED",
        decorator : "main",
        iconPosition : "left",
        padding : 5,
        allowGrowY: false,
        cursor: "pointer"
    });

    var lastEdit = new qx.ui.basic.Label().set({
        rich : true,
        font: new qx.bom.Font.fromString("11px sans-serif"),
        textColor: "green",
        paddingTop: 6
    });

    if (assignment.submission.id != 0) {
        // last edit
        lastEdit.setValue( "<strong>Last edition:</strong> " + readableDate(assignment.submission.timemodified) );
        mainContainer.add(lastEdit);

        // file
        if (assignment.submission.files[0] != null) {
            file.setLabel(assignment.submission.files[0].filename);
            mainContainer.add(file);
        }
    }

    box1.add(chooseFile);
    box2.add(save);
    box2.add(cancel);

    mainContainer.add(box1);

    // actions
    chooseFile.addListener("execute", function(e) {
        var dialog = new eyeos.dialogs.FileChooser(checknum);

        dialog.showOpenDialog(this._window, function(choice, path) {
            if (choice == eyeos.dialogs.FileChooser.APPROVE_OPTION) {
                mainContainer.remove(box1);
                // file choosed
                file.setLabel(path);

                mainContainer.add(file);
                mainContainer.add(box2);
            }
        }, this, null);

        // center dialog
        //dialog.center();
    });

    cancel.addListener("execute", function(e) {
        mainContainer.remove(box2);
        if (assignment.submission.files[0] != "") {
//            file.setLabel(assignment.submission.files[0].fileurl)
        } else {
            mainContainer.remove(file);
        }
        mainContainer.add(box1);
    });

    save.addListener("execute", function(e) {
        save.setEnabled(false);
        var loading = new qx.ui.basic.Image("index.php?extern=/images/moodle/theme/ajax-loader.gif").set({
            paddingTop:5
        });
        box2.add(loading);

        // if is new submission
        if (assignment.submission.id == 0) {
            assignment.submission.assignment = assignment.id;
            assignment.submission.assignmenttype = assignment.assignmenttype;
//            assignment.submission.userid = 2; // TODO
            assignment.submission.timecreated =  new Date().getTime();
//            assignment.submission.username = "admin"; // TODO
//            assignment.submission.useremail = "yakukubu@hotmail.com"; // TODO
        }

        // new file


        var newFile = new Object;
        newFile.filepath = file.getLabel();
        assignment.submission.files = [newFile]; // array

//        assignment.submission.files[0].fileurl = "";
//        assignment.submission.files[0].filename = "";
//        assignment.submission.files[0].filepath = file.getLabel(); // instead "/"
//        assignment.submission.files[0].filesize = "";
//        assignment.submission.files[0].filecontent = "";

        eyeos.callMessage(checknum, 'updateSubmission', assignment.submission, function (rPars) {
            box2.remove(loading);
            mainContainer.remove(box2);

            // effect for label
            lastEdit.setValue("<strong>Last edition:</strong> " + readableDate( Math.round( new Date().getTime() / 1000 ) ));
			
			
			if (mainContainer.indexOf(lastEdit) == "-1") {
				mainContainer.add(lastEdit);
				
				// Qooxdoo has little delay adding, so we must wait a little to get the DOM of the label
				lastEdit.addListener('appear', function() {
					var pulsate = new qx.fx.effect.combination.Pulsate(lastEdit.getContentElement().getDomElement());
					pulsate.start();
				});
			
            } else {
				var pulsate = new qx.fx.effect.combination.Pulsate(lastEdit.getContentElement().getDomElement());
				pulsate.start();
			}
			
            mainContainer.add(box1);
            save.setEnabled(true);
        });
		
    });

    return mainContainer;
}

/*
 * Decorator: Advanced uploading of files
 */
function multipleFiles(mainContainer) {
    return mainContainer;
}